import os

import requests
from openai import OpenAI
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage,AIMessage,SystemMessage

#获取.env文件中的内容
from dotenv import load_dotenv
load_dotenv()

API_KEY = os.getenv("API_KEY")
API_BASE_URL = os.getenv("API_BASE_URL")
MODEL_NAME = os.getenv("MODEL_NAME")



# 创建OpenAI客户端
class OpenAIClient:
    def __init__(self, api_key = API_KEY):
        self.client = OpenAI(api_key=api_key,base_url = API_BASE_URL,)


    def get_avaliable_models(self):
        models = self.client.models.list()
        return [model.id for model in models.data]

    def get_audio_list(self):


        headers= {
            "Authorization": f"Bearer {API_KEY}",
        }
        request = requests.get(f"{API_BASE_URL}/voice/list",headers=headers)

        print(request.json())



#创建langchain模型类
class LangChainModel:
    def __init__(self, model_name=MODEL_NAME, api_key=API_KEY):
        self.model = ChatOpenAI(model=model_name, api_key=api_key,base_url=API_BASE_URL)

    async def chat(self, messages_list,user_message):
        #处理获取到的messages
        messages_list = [SystemMessage(content=message["content"]) if message["message_type"] == "system" else HumanMessage(content=message["content"]) if message["message_type"] == "user" else AIMessage(content=message["content"]) for message in messages_list]
        messages_list.append(HumanMessage(content=user_message))
        async for chunk in self.model.astream(messages_list):

            if chunk.content:
                yield chunk.content




if __name__ == "__main__":
    client = OpenAIClient()
    client.get_audio_list()
    # print(client.get_avaliable_models())
    # model = LangChainModel()
    # generator = model.chat([{"message_type": "system", "content": "你是李白"}], "请写一首关于诗的诗")
    # while True:
    #     print(next(generator))